//
//  FactoryNewProductViewController.m
//  ShoppingExperience
//
//  Created by LiYinDi on 15/8/12.
//  Copyright (c) 2015年 RuiBen. All rights reserved.
//

#import "FactoryNewProductViewController.h"
#import "FactoryNewProductLeftTableViewCell.h"
#import "FactoryNewProductRightTableViewCell.h"
#import "UIImageView+WebCache.h"
@interface FactoryNewProductViewController ()<NewProductRightDelegate>
{
    
    NSMutableArray *leftItypeCodeArray;
    NSMutableArray *leftCompanyCodeArray;
    NSMutableArray *leftISectypeCodeArray;
    NSMutableArray *leftUrlArray;
    NSMutableArray *leftOnHandArray;
    NSMutableArray *leftTitleArray;
    
    NSUInteger _rightPageIndex;
    NSUInteger _rightTotalCount;
    NSUInteger _rightTotalPage;
    
    NSMutableArray *rightItemCodeArray;
    NSMutableArray *rightCompanyCodeArray;
    NSMutableArray *rightItemNameArray;
    NSMutableArray *rightAddressArray;
    NSMutableArray *rightPriceArray;
    NSMutableArray *rightUrlArray;
    NSMutableArray *rightWeightArray;
    NSMutableArray *rightSeriesNameArray;
    NSMutableArray *rightTypeNameArray;
    NSMutableArray *rightInDateArray;
    
    NSInteger leftTableTag;
    

}
@end

@implementation FactoryNewProductViewController
-(void)viewWillAppear:(BOOL)animated
{
    [Global setHomeCustomID:35];
   leftItypeCodeArray=[NSMutableArray array];
   leftCompanyCodeArray=[NSMutableArray array];
   leftISectypeCodeArray=[NSMutableArray array];
   leftUrlArray=[NSMutableArray array];
   leftOnHandArray=[NSMutableArray array];
   leftTitleArray=[NSMutableArray array];
    
    rightItemCodeArray=[NSMutableArray array];
    rightCompanyCodeArray=[NSMutableArray array];
    rightItemNameArray=[NSMutableArray array];
    rightAddressArray=[NSMutableArray array];
    rightPriceArray=[NSMutableArray array];
    rightUrlArray=[NSMutableArray array];
    rightWeightArray=[NSMutableArray array];
    rightSeriesNameArray=[NSMutableArray array];
     rightTypeNameArray=[NSMutableArray array];
     rightInDateArray=[NSMutableArray array];
    [_leftTableView setBackgroundColor:[UIColor clearColor]];
    leftTableTag=0;
    [self requestSeriesList];
}
-(void)requestSeriesList
{
    
    if ([Global getLoginToken].length>0) {
      //  [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:[Global getLoginToken] forKey:@"Token"];
        
        [HttpRequest requestData:@"Manufacturer/PlatFormSeriesList" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                   //  NSLog(@"tt=%@",severDataDict.dataDict);
                     //[Global hideProgressHUDInternal:self.view];
                 //   NSLog(@"sdfsfsfsfsfsf");
                    [Global hideProgressHUDInternal:self.view];
                    [leftItypeCodeArray removeAllObjects];
                    [leftCompanyCodeArray removeAllObjects];
                    [leftISectypeCodeArray removeAllObjects];
                    [leftUrlArray removeAllObjects];
                    [leftOnHandArray removeAllObjects];
                    [leftTitleArray removeAllObjects];

                   NSMutableArray * mSeriesArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                    for (int i=0; i<mSeriesArray.count; i++) {
                        [leftItypeCodeArray addObject:[[mSeriesArray objectAtIndex:i] objectForKey:@"ItypeCode"]];
                        [leftCompanyCodeArray addObject:[[mSeriesArray objectAtIndex:i] objectForKey:@"CompanyCode"]];
                        [leftISectypeCodeArray addObject:[[mSeriesArray objectAtIndex:i] objectForKey:@"ISectypeCode"]];
                       
                        //[leftUrlArray addObject:[[mSeriesArray objectAtIndex:i] objectForKey:@"ImageUrl"]];
                        [leftOnHandArray addObject:[[mSeriesArray objectAtIndex:i] objectForKey:@"OnHand"]];
                        [leftTitleArray addObject:[[mSeriesArray objectAtIndex:i] objectForKey:@"ISectypeName"]];
                    }
                 //   NSLog(@"leftISectypeCodeArray=====%@",leftISectypeCodeArray);
                    //                    NSIndexPath *ip= [NSIndexPath indexPathForRow:_selectID inSection:0];
                    //                    [_leftTableView selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionBottom];
                    
                    [_leftTableView reloadData];
                    if (mSeriesArray.count>0&&leftISectypeCodeArray.count>0&&leftCompanyCodeArray.count>0&&leftItypeCodeArray.count
                        >0) {
                        
                        NSIndexPath *ip=[NSIndexPath indexPathForRow:leftTableTag inSection:0];
                        [_leftTableView selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionBottom];
                        [rightItemCodeArray removeAllObjects];
                        [rightItemNameArray removeAllObjects];
                        [rightCompanyCodeArray removeAllObjects];
                        [rightAddressArray removeAllObjects];
                        [rightPriceArray removeAllObjects];
                        [rightUrlArray removeAllObjects];
                        [rightWeightArray removeAllObjects];
                        [rightSeriesNameArray removeAllObjects];
                        [rightTypeNameArray removeAllObjects];
                        [rightInDateArray removeAllObjects];
                        
                        _rightPageIndex=0;
                        [self loadRightNextPage:_rightPageIndex];
                    }
                }
                else
                {
                  //  [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
//                    UIViewController *controller=[[GlobalViewController alloc]init];
//                    [self.navigationController pushViewController:controller animated:YES];
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                         [Global loginViewController:self noteStr:requestResultStr];
                       // [Global loginViewController:self];
                    }

                }
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
        
    }
    
}
-(void) loadRightNextPage:(NSUInteger)oldPageNum {
    if(oldPageNum!=0 && _rightTotalCount<=rightItemCodeArray.count)
        return;
    if(oldPageNum == 0){
        [rightItemCodeArray removeAllObjects];
        [_rightTableView reloadData];
    }
    _rightPageIndex=oldPageNum+1;
    [self requestRightList: _rightPageIndex pageSize:6];
}
-(void)requestRightList:(NSUInteger)pageIndex pageSize:(NSUInteger)pageSize
{
    if ([Global getLoginToken].length>0) {
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:[Global getLoginToken] forKey:@"Token"];
        NSNumber *pageSizeNumber = [NSNumber numberWithInteger:pageSize];
        NSNumber *pageIndexNumber = [NSNumber numberWithInteger:pageIndex];
        //        NSString *pageSizeStr=[NSString stringWithFormat:@"%d",pageSize];
        //        NSString *pageIndexStr=[NSString stringWithFormat:@"%d",pageIndex];
        
        [params setObject:pageSizeNumber forKey:@"PageSize"];
        [params setObject:pageIndexNumber forKey:@"PageIndex"];
        if (leftISectypeCodeArray!=nil&&leftISectypeCodeArray.count>leftTableTag) {
            
        
        [params setObject:[leftISectypeCodeArray objectAtIndex:leftTableTag] forKey:@"ISecTypeCode"];
        }
        if (leftCompanyCodeArray!=nil&&leftCompanyCodeArray.count>leftTableTag) {
            
        [params setObject:[leftCompanyCodeArray objectAtIndex:leftTableTag] forKey:@"CompanyCode"];
        }
        if (leftItypeCodeArray!=nil&&leftItypeCodeArray.count>leftTableTag) {
            
         [params setObject:[leftItypeCodeArray objectAtIndex:leftTableTag] forKey:@"ItypeCode"];
        }
        
        [HttpRequest requestData:@"Manufacturer/PlatFormItemList" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    // NSLog(@"seve2222====%@",severDataDict.dataDict);
                    _rightTotalCount=[[severDataDict.dataDict objectForKey:@"TotalCount"] integerValue];
                    
                    if (_rightTotalCount%6!=0) {
                        _rightTotalPage=_rightTotalCount/6+1;
                    }
                    else if (_rightTotalCount%6==0)
                    {
                        _rightTotalPage=_rightTotalCount/6;
                    }
                    NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                    //  NSLog(@"mMembersArray===%@",mMembersArray);
                    if ( mItemsArray.count>0) {
                        for (int i=0; i< mItemsArray.count; i++) {
                            
                            [rightItemCodeArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"ItemCode"]];
                            [rightWeightArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"Gram"]];
                            [rightPriceArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"Price"]];
                            [rightUrlArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"ImageUrl"]];
                            [rightAddressArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"WhsName"]];
                            [rightItemNameArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"ItemName"]];
                            [rightCompanyCodeArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"CompanyCode"]];
                            [rightSeriesNameArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"SeriesName"]];
                            [rightTypeNameArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"ItypeName"]];
                            [rightInDateArray addObject:[[mItemsArray objectAtIndex:i] objectForKey:@"InDate"]];

                            
                        }
                    }
                    //   NSLog(@"itemUrlArray7777===%@",itemUrlArray);
                    
                    [_rightTableView reloadData];
                    
                    
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                         [Global loginViewController:self noteStr:requestResultStr];
                       // [Global loginViewController:self];
                    }

                }
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
               // [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
        
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView==_leftTableView) {
        return leftItypeCodeArray.count;
    }
    
    else if(tableView==_rightTableView)
    {
        return rightItemCodeArray.count;
    }
    else
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_leftTableView) {
        return 90;
    }
    else if(tableView==_rightTableView)
        return 120;
       else
        return 50;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView==_leftTableView) {
        
        
        static NSString * const  leftIdentifier = @"leftIdentifier";
        FactoryNewProductLeftTableViewCell *cell=( FactoryNewProductLeftTableViewCell *)[tableView dequeueReusableCellWithIdentifier: leftIdentifier];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FactoryNewProductLeftTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame] ;
        cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
          //  if (leftUrlArray.count>0) {
//            if ([leftUrlArray objectAtIndex:indexPath.row]!=[NSNull null]&&[[leftUrlArray objectAtIndex:indexPath.row] length]>0) {
//                [ cell.productImage setImageWithURL:[NSURL URLWithString:[leftUrlArray objectAtIndex:indexPath.row] ]];
//            }
//            else
//            {
//                [cell.productImage setImage:[UIImage imageNamed:@"zhanweitu_.png"]];
//            }

       // }
        if (leftOnHandArray.count>0) {
            cell.productContentLabel.text=[NSString stringWithFormat:@"共有%d款商品",[[leftOnHandArray objectAtIndex:indexPath.row] integerValue]];
        }
        if (leftTitleArray.count>0) {
            cell.productTitleLabel.text=[leftTitleArray objectAtIndex:indexPath.row];
        }
        return cell;
    }
//    else if(tableView==_rightTableView)
    else
    {
        static NSString * const  rightIdentifier = @"rightIdentifier";
        FactoryNewProductRightTableViewCell *cell=( FactoryNewProductRightTableViewCell *)[tableView dequeueReusableCellWithIdentifier: rightIdentifier];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FactoryNewProductRightTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
           cell.delegate=self;
        }
        cell.addToSaleBtn.tag=indexPath.row;
       
        if (rightUrlArray.count>0) {
            if ([rightUrlArray objectAtIndex:indexPath.row]!=[NSNull null]&&[[rightUrlArray objectAtIndex:indexPath.row] length]>0) {
                [ cell.productImage setImageWithURL:[NSURL URLWithString:[rightUrlArray objectAtIndex:indexPath.row] ]];
            }
            else
            {
                [cell.productImage setImage:[UIImage imageNamed:@"zhanweitu_.png"]];
            }
            
        }
        if (rightItemCodeArray.count>0) {
            if ([rightItemNameArray objectAtIndex:indexPath.row]!=[NSNull null]&&[rightItemNameArray objectAtIndex:indexPath.row]!=[NSNull null]) {
                cell.productTitleLable.text=[NSString stringWithFormat:@"%@ %@",[rightItemCodeArray objectAtIndex:indexPath.row],[rightItemNameArray objectAtIndex:indexPath.row]];
            }
        }
        if (rightPriceArray.count>0) {
            if ([rightPriceArray objectAtIndex:indexPath.row]!=[NSNull null])
            {
                float AvgPrice=[[rightPriceArray objectAtIndex:indexPath.row] floatValue];
                NSString *AvgPriceStr=[Global floatConvertPercentile:AvgPrice];
                
                cell.productPriceLabel.text=[NSString stringWithFormat:@"¥%@",AvgPriceStr];
            }
        }
        if(rightAddressArray.count>0)
            
        {
            if ([rightAddressArray objectAtIndex:indexPath.row]!=[NSNull null])
            {
                cell.productAddressLabel.text=[rightAddressArray objectAtIndex:indexPath.row];
            }
        }
        if (rightWeightArray.count>0) {
            if ([rightWeightArray objectAtIndex:indexPath.row]!=[NSNull null])
            {
                cell.productWeightLabel.text=[NSString stringWithFormat:@"%0.02fg",[[rightWeightArray objectAtIndex:indexPath.row] floatValue]];
                //[self resizeLabel: cell.productWeightLabel];
                CGRect frame= cell.productPriceLabel.frame;
                frame.origin.x=cell.productWeightLabel.frame.origin.x+cell.productWeightLabel.frame.size.width+25;
                cell.productPriceLabel.frame=frame;
            }
        }
        
        if (indexPath.row == [rightItemCodeArray count] - 1)
        {
            if (_rightPageIndex<=_rightTotalPage) {
                //  NSLog(@"###LOADING???");
                [self loadRightNextPage:_rightPageIndex];
            }
        }
        
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_leftTableView) {
        [rightItemCodeArray removeAllObjects];
        [rightItemNameArray removeAllObjects];
        [rightAddressArray removeAllObjects];
        [rightPriceArray removeAllObjects];
        [rightUrlArray removeAllObjects];
        [rightWeightArray removeAllObjects];
       
        
        
        //        NSIndexPath *indexPath1= [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
        //        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath1];
        //        ProductCommonTableViewCell *leftCell=( ProductCommonTableViewCell *)cell;
        //       leftCell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
        leftTableTag=indexPath.row;
        
        _rightPageIndex=0;
        [self loadRightNextPage:_rightPageIndex];
    }
     else if (tableView==_rightTableView)
    {
        if (rightItemCodeArray.count>0) {
           //  NSLog(@"ddddooooooo1111111");
          //  if ([self.delegate respondsToSelector:@selector(newProductRightTableView:code:companyCodeStr:_itemCodeArray:_itemNameArray:_itemWhereArray:_itemPriceArray:_itemUrlArray:_itemWeightArray:_itemSeriesNameArray:_itemTypeNameArray:_itemInDateArray:)]) {
              //  NSLog(@"ddddooooooo");
                
                [self.delegate newProductRightTableView:indexPath.row code:[rightItemCodeArray objectAtIndex:indexPath.row] companyCodeStr:[rightCompanyCodeArray objectAtIndex:indexPath.row]  _itemCodeArray:rightItemCodeArray _itemNameArray:rightItemNameArray _itemWhereArray:rightAddressArray _itemPriceArray:rightPriceArray _itemUrlArray:rightUrlArray _itemWeightArray:rightWeightArray _itemSeriesNameArray:rightSeriesNameArray _itemTypeNameArray:rightTypeNameArray _itemInDateArray:rightInDateArray];
            }
       // }
    }
    
    
}
-(void)addToSaleClick:(NSUInteger)tag
{
    if ([Global getLoginToken].length>0) {
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:[Global getLoginToken] forKey:@"Token"];
        [params setObject:[rightItemCodeArray objectAtIndex:tag] forKey:@"ItemCode"];
         [params setObject:[rightCompanyCodeArray objectAtIndex:tag] forKey:@"CompanyCode"];
    
        //  NSLog(@"addToShopCartParams===%@",params);
        [HttpRequest requestData:@"Manufacturer/AddShopCart" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    
                    // NSLog(@"addToShopCart===%@",severDataDict.dataDict);
                    //                        if ([self.delegate respondsToSelector:@selector(product_SeriesShopCartClick)]) {
                    //
                    //                            [self.delegate product_SeriesShopCartClick];
                    //                        }
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                         [Global loginViewController:self noteStr:requestResultStr];
                      //  [Global loginViewController:self];
                    }

                }
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
    }
    

}
-(void)resizeLabel:(UILabel *)aLabel
{
    aLabel.lineBreakMode =NSLineBreakByWordWrapping;
    aLabel.numberOfLines =0;
    
    NSString *contentStr=aLabel.text;
    //if (contentStr) {
    aLabel.autoresizesSubviews = YES;
    aLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:contentStr];
    aLabel.attributedText = attrStr;
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attribute = @{NSFontAttributeName:aLabel.font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    CGSize textSize = [aLabel.text boundingRectWithSize:CGSizeMake(1000,aLabel.frame.size.height) // 用于计算文本绘制时占据的矩形块
                                                options:NSStringDrawingUsesLineFragmentOrigin //| NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                             attributes:attribute        // 文字的属性
                                                context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    CGRect frame = CGRectMake(aLabel.frame.origin.x, aLabel.frame.origin.y,textSize.width, aLabel.frame.size.height );
    aLabel.frame=frame;
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
